<template>
  <div class="permission-list">
    <div class="page-header">
      <h2>权限管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增权限
      </el-button>
    </div>

    <el-card>
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入权限名称、代码或描述"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择类型"
            clearable
            style="width: 120px"
          >
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        style="width: 100%"
      >
        <el-table-column prop="display_name" label="权限名称" width="200" />
        <el-table-column prop="code" label="权限代码" width="200" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'menu' ? 'primary' : 'success'">
              {{ row.type === 'menu' ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="icon" label="图标" width="80">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>


    </el-card>

    <!-- 权限表单弹窗 -->
    <PermissionForm
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { getPermissionTree, deletePermission } from './api'
import PermissionForm from './form.vue'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const originalData = ref([]) // 保存原始数据用于搜索
const formVisible = ref(false)
const formData = ref(null)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: '',
  status: null
})



// 获取权限树数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await getPermissionTree()
    console.log('权限树API响应:', response)

    // 保存原始数据和显示数据
    const data = response.data.data || response.data || []
    originalData.value = data
    tableData.value = data
    console.log('权限树数据:', tableData.value)
  } catch (error) {
    ElMessage.error('获取权限列表失败')
    console.error('获取权限失败:', error)
  } finally {
    loading.value = false
  }
}



// 树形数据搜索过滤
const filterTreeData = (data, keyword, type, status) => {
  const filtered = []

  for (const item of data) {
    // 检查当前节点是否匹配搜索条件
    const matchesKeyword = !keyword ||
      item.name?.toLowerCase().includes(keyword.toLowerCase()) ||
      item.display_name?.toLowerCase().includes(keyword.toLowerCase()) ||
      item.description?.toLowerCase().includes(keyword.toLowerCase()) ||
      item.code?.toLowerCase().includes(keyword.toLowerCase())

    const matchesType = !type || item.type === type
    const matchesStatus = status === null || status === undefined || item.status === status

    // 递归过滤子节点
    const filteredChildren = item.children ? filterTreeData(item.children, keyword, type, status) : []

    // 如果当前节点匹配条件，或者有匹配的子节点，则保留该节点
    if (matchesKeyword && matchesType && matchesStatus) {
      // 当前节点匹配，保留所有子节点
      filtered.push({
        ...item,
        children: item.children || []
      })
    } else if (filteredChildren.length > 0) {
      // 当前节点不匹配，但有匹配的子节点，保留该节点和匹配的子节点
      filtered.push({
        ...item,
        children: filteredChildren
      })
    }
  }

  return filtered
}

// 搜索
const handleSearch = () => {
  const { keyword, type, status } = searchForm

  if (!keyword && !type && status === null) {
    // 没有搜索条件，显示所有数据
    tableData.value = originalData.value
  } else {
    // 有搜索条件，进行过滤
    tableData.value = filterTreeData(originalData.value, keyword, type, status)
  }
}

// 重置搜索
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.type = ''
  searchForm.status = null
  // 重置后显示所有数据
  tableData.value = originalData.value
}

// 新增
const handleAdd = () => {
  formData.value = null
  formVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  formData.value = { ...row }
  formVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${row.display_name || row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deletePermission(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}



// 表单提交成功
const handleFormSuccess = () => {
  formVisible.value = false
  fetchData()
}

// 监听搜索表单变化，实现实时搜索
watch(
  () => [searchForm.keyword, searchForm.type, searchForm.status],
  () => {
    handleSearch()
  },
  { deep: true }
)

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
}


</style>
